const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");

// 补货提醒
router.post('/report/bhtx', async ctx => {
    let user = ctx.user
    let body = ctx.request.body
    let formData = body.formData
    let tenantId = user.tenantId;
    let beginDate = formData.beginDate ? formData.beginDate: '2001-01-01';
    let endDate = formData.endDate?formData.endDate:tool.getDay();
    let buId = formData.buId?formData.buId:0;
    let invId = formData.invId?formData.invId:0;
    let salesId = formData.salesId?formData.salesId:0;
    let currentPage = body.currentPage?body.currentPage:1;
    let pageSize = body.pageSize?body.pageSize:200;
    let offset = (currentPage-1) * pageSize;
    let excel = body.excel
    await db.query(`exec update_stock_bh @tenantId=${tenantId}`, {type: QueryTypes.UPDATE})
    // 均线

    let sqls = `select * from stock_bh where tenantId=${tenantId}  `
    if(buId) {
        sqls += ` and buId=${buId} `
    }
    if(invId) {
        sqls += ` and invId=${invId} `
    }
    if(excel) {
        sqls += ` buId,invId,supportDays  `
        let list = await db.query(sqls, {type: QueryTypes.SELECT})
        return tool.doExcelOut(ctx, list)
    }
    else {
        let sort = tool.getSort(ctx)
        let sorts = ' buId,invId,supportDays  '
        if(sort) sorts = sort
        let totalModel = await db.query(`select count(*) total from (${sqls}) a `, {type: QueryTypes.SELECT, plain: true})
        sqls = ` select * from (${sqls}) a order by ${sorts} offset ${offset} rows fetch next ${pageSize} rows only;`
        let list = await db.query(sqls, {type: QueryTypes.SELECT})
        return ctx.suc('', {
            total: totalModel?totalModel.total: 0,
            list: list
        })
    }

})



module.exports = router;
